$(function () {

    //读取配置
    readConf();
    $("#jcodeAction").click(function () {
        if (validate()==false) {
            alert("请输入必填项");
            return;
        }
        $("#jcodeAction").prop("disabled", "disabled");
        $.ajax({
            type: "post",
            dataType: "json",
            url: "/autoJCode?t=" + new Date().getTime(),
            contentType: "application/json;charset=UTF-8",//指定消息请求类型
            data: JSON.stringify(buildJson()),//将js对象转成json对象
            success: function (data) {
                console.log(data);
                if (data.message == "success") {
                    alert(data.data)
                }
                $("#jcodeAction").removeAttr("disabled");
            }, error: function () {
                alert("生成失败，异常");
                $("#jcodeAction").removeAttr("disabled");
            }
        });
    })
    $("#saveConfig").click(function () {
        saveConf();
    })
})

function validate() {
    if (getEmpty("group")||getEmpty("artifact")||getEmpty("address") || getEmpty("dbUser") || getEmpty("dbPassword")) {
        return false;
    }
    return true;
}

function buildJson() {
    var json = {
        "group": getVal("group"),
        "artifact": getVal("artifact"),
        "author": getVal("author"),
        "version": getVal("version"),
        "db": {
            "ip": getVal("address").replace('：', ':'),
            "dataBaseName": getVal("dataBaseName"),
            "user": getVal("dbUser"),
            "password": getVal("dbPassword")
        },
        "diskPath": getVal("localPath"),
        "tableName": ""
    }
    return json;
}

function setForm(json) {
    var val = JSON.parse(json)
    setVal("group", val.group);
    setVal("artifact", val.artifact);
    setVal("author", val.author);
    setVal("version", val.version);
    setVal("address", val.db.ip);
    setVal("dataBaseName", val.db.dataBaseName);
    setVal("dbUser", val.db.user);
    setVal("password", val.db.password);
    setVal("diskPath", val.diskPath);
}

function getVal(id) {
    return $("#" + id).val().trim();
}

function getEmpty(id) {
    return $("#" + id).val().trim() == '';
}

function setVal(id, value) {
    return $("#" + id).val(value);
}

function saveConf() {
    var key = $('#confName').val().trim();
    if (key == '') {
        return;
    }
    localStorage.setItem(key, JSON.stringify(buildJson()));
    location.reload();
}

function readConf() {
    var storage = window.localStorage;
    var menu = '';
    for (var i = 0, len = storage.length; i < len; i++) {
        var key = storage.key(i);
        menu += '<li><a href="#" onclick="writeconf(this)">' + key + '</a></li>';
    }
    $('#savedConf').append(menu);
}

function writeconf(ob) {
    var index = $(ob).index();
    var key = $(ob).eq(index).text();
    var value = localStorage.getItem(key);
    if (value != null) {
        setForm(value);
    }
}